package com.dxtan90.strategy.impl;

import com.dxtan90.strategy.BaseStrategy;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author shijunhao
 * @since 2024/4/16 14:03
 */
public class Xsbook extends BaseStrategy {

    @Override
    public String getSourceUrl() {
        return "http://www.xsbook.cc";
    }

    @Override
    public String getCategoryName() {
        return "xsbook";
    }

    @Override
    public String parseTitle(Document document) {
        return Optional.ofNullable(document.getElementById("info"))
                .map(elements -> elements.child(0))
                .map(Element::text)
                .orElse("noneTitle_" + System.currentTimeMillis());
    }

    @Override
    public List<String> parseCategory(Document document) {
        Elements dl = Optional.ofNullable(document.getElementsByTag("dd")).orElse(new Elements());
        List<String> category = new ArrayList<>();
        for (Element dd : dl) {
            Optional.of(dd.child(0)).ifPresent(a -> {
                category.add(a.attr("href"));
            });
        }
        return category;
    }

    @Override
    public List<String> parseContent(Document document) throws IOException {
        List<String> sectionList = new ArrayList<>();
        String text = Optional.ofNullable(document.getElementById("content"))
                .map(Element::html)
                .orElse("");
        String[] split = text.split("<br>");
        for (String s : split) {
            if (!StringUtils.isBlank(s)) {
                Document lineDoc = Jsoup.parse(s);
                String newText = lineDoc.text();
                sectionList.add(newText);
            }
        }
        return sectionList;
    }

}